package asia.redact.bracket.exampleclasses;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import asia.redact.bracket.properties.serializer.Loadable;

/**
 * Example of a Loadable. Setter knows how to instantiate and set objects which implement this interface
 * 
 * @author Dave
 *
 */
public class LoadableDate implements Loadable {
	
	public static final String defaultFormat = "yyMMddHHmmssSSSZ"; // for example, 130615135823041+1000
	final SimpleDateFormat format;
	Date date;
	
	public LoadableDate() {
		this.date = new Date();
		format = new SimpleDateFormat(defaultFormat);
	}

	public LoadableDate(Date date) {
		this.date = date;
		format = new SimpleDateFormat(defaultFormat);
	}
	
	public LoadableDate(SimpleDateFormat format, Date date) {
		this.date = date;
		this.format = format;
	}

	@Override
	public void fromString(String stringRepresentation) {
		try {
			date = format.parse(stringRepresentation);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("Failed to parse stringRepresentation: "+stringRepresentation);
		}
		
	}
	
	public String toString() {
		return format.format(date);
	}


	public SimpleDateFormat getFormat() {
		return format;
	}


	public Date getDate() {
		return date;
	}


	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((date == null) ? 0 : date.hashCode());
		result = prime * result + ((format == null) ? 0 : format.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		LoadableDate other = (LoadableDate) obj;
		if (date == null) {
			if (other.date != null)
				return false;
		} else if (!date.equals(other.date))
			return false;
		if (format == null) {
			if (other.format != null)
				return false;
		} else if (!format.equals(other.format))
			return false;
		return true;
	}

}
